<template>
    <div class="flex flex-col items-center text-center">
        <div class="text-5xl font-bold text-white mb-2 font-playball tracking-widest">
            <span>{{ displayValue }}</span>
            <span v-if="suffix">{{ suffix }}</span>
        </div>
        <div class="text-lg text-white/60 mb-4 tracking-wide">
            <slot name="title"></slot>
        </div>
        <p class="text-white/70 text-sm font-poppins tracking-wide">
            <slot></slot>
        </p>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
    name: 'Counter',
    props: {
        /*
        * 结束值
        */
        endValue: {
            type: Number,
            required: true
        },
        /*
        * 持续时间
        */
        duration: {
            type: Number,
            default: 1000
        },
        /*
        * 开始延迟
        */
        startDelay: {
            type: Number,
            default: 0
        },
        /*
        * 后缀
        */
        suffix: {
            type: String,
            default: ''
        },
        /*
        * 前缀
        */
        prefix: {
            type: String,
            default: ''
        },
        /*
        * 是否触发
        */
        triggered: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            /*
            * 显示值
            */
            displayValue: 0,
            /*
            * 开始时间
            */
            startTime: 0,
            /*
            * 动画ID
            */
            animationId: 0
        };
    },
    watch: {
        triggered(newVal) {
            if (newVal) {
                this.startAnimation();
            }
        }
    },
    mounted() {
        if (this.triggered) {
            this.startAnimation();
        }
    },
    methods: {
        /*
        * 动画
        */
        animate(timestamp: number) {
            if (!this.startTime) {
                this.startTime = timestamp;
            }
            
            const runtime = timestamp - this.startTime;
            const progress = Math.min(runtime / this.duration, 1);
            
            if (progress < 1) {
                this.displayValue = Math.floor(this.endValue * progress);
                this.animationId = requestAnimationFrame(this.animate);
            } else {
                this.displayValue = this.endValue;
            }
        },
        /*
        * 开始动画
        */
        startAnimation() {
            if (this.startDelay > 0) {
                setTimeout(() => {
                    this.animationId = requestAnimationFrame(this.animate);
                }, this.startDelay);
            } else {
                this.animationId = requestAnimationFrame(this.animate);
            }
        }
    }
});
</script> 